package com.canin.member.action;

import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import com.canin.Constant;
import com.canin.dao.DAOFactory;
import com.canin.dao.MemberDAO;

import com.canin.model.Member;
import com.opensymphony.xwork2.ActionSupport;

public class MemberAction extends ActionSupport implements SessionAware {

	private static final long serialVersionUID = 3192352560071623944L;
	
	private Map<String, Object> userSession;
	private Member memberForm = new Member();
	private Member member = new Member();
	
	public String main()
	{
		return "main";
	}
	
	public String toEdit()
	{
		Member member = (Member)userSession.get( Constant.MEMBER );
		memberForm = new Member();
		memberForm.setFirst_Name( member.getFirst_Name() );
		memberForm.setLast_Name( member.getLast_Name() );
		memberForm.setEmail( member.getEmail() );
		memberForm.setTelephone( member.getTelephone() );
		memberForm.setAddress_Line1( member.getAddress_Line1() );
		memberForm.setAddress_Line2( member.getAddress_Line2() );
		memberForm.setAddress_Line3( member.getAddress_Line3() );
		memberForm.setAddress_Line4( member.getAddress_Line4() );
		memberForm.setPost_Code( member.getPost_Code() );
		
		userSession.put(Constant.MEMBER, member);
		
		return "toEdit";
	}
	
	public String edit() throws Exception
	{
		member = (Member)userSession.get( Constant.MEMBER );

//		addActionMessage("edit --> " + member.getFirst_Name()
//				+ " id: " + member.getMemberId() + " : " + memberForm.getFirst_Name());
		
		memberForm.setMemberId( member.getMemberId() );
		
		DAOFactory daoFactory = new DAOFactory();
		daoFactory.beginConnection();

		MemberDAO memberDAO = daoFactory.createMemberDAO();
		memberDAO.updateMember( memberForm );
		
		userSession.put(Constant.MEMBER, refresh());
		addActionMessage( "แก้ไขข้อมูล เสร็จสมบูรณ์" );
		
		return "edit";
	}
	
	public Member refresh() throws Exception
	{
		Member tmpMember = new Member();
		member = (Member)userSession.get( Constant.MEMBER );
		
//		addActionMessage("refresh " + member.getMemberId());
		
		DAOFactory daoFactory = new DAOFactory();
		daoFactory.beginConnection();

		MemberDAO memberDAO = daoFactory.createMemberDAO();
		tmpMember = memberDAO.getMemberById( member.getMemberId() );
			
		return tmpMember;
	}
	
	
	
	
	
	

	public Member getMemberForm()
	{
		return memberForm;
	}

	public void setMemberForm(Member member)
	{
		this.memberForm = member;
	}
	
	public Member getMember()
	{
		return member;
	}

	public void setMember(Member member)
	{
		this.member = member;
	}

	@Override
	public void setSession(Map<String, Object> userSession)
	{
		this.userSession = userSession;
		
	}
}
